
class DateRangeField < NamedDecorator
  attribute :from
  attribute :to

  def class_body
    if name && name.length > 0
      "property :#{name}_from, Date\n"+
      "property :#{name}_to, Date\n"
    end
  end

#  def creator e
#    InputText.new(:name => (form_id :value), :value => value)
#  end

  def thingswecanadd
    [DateRangeThing]
  end

  def creator e
    if child
      "before create".print
      child.from = from
      child.to = to
      child.creator(e)
    end
  end

  def from
    if root.respond_to? name+'_from'
      "from is".print
      root.send(name+'_from').print
    else
      @from
    end
  end

  def to
    if root.respond_to? name+'_to'
      "to is".print
      root.send(name+'_to').print
    else
      @to
    end
  end

  def from= v
    if root.respond_to? name+'_from='
      root.send(name+"_from=", v)
      if child
        child.from = v
      end
    else
      @from = v
    end
  end

  def to= v
    root.respond_to?(name+'_to=').printi
    if root.respond_to?(name+'_to=')
    "set TO to #{v}".printi
    root.send(name+'_to').print
      root.send(name+"_to=", v)
      if child
        child.to = v
      end
    else
      @to = v
    end
  end

  def recieve e
    if child
      child.from = from
      child.to = to

      child.recieve(e)

      self.from = child.from
      self.to = child.to
    end
    super
  end

  def filters
    [WithinRange]
  end
end


class WithinRange < Thing
  attribute :range

  def initialize range
    self.range = range
  end

  def call value
    @range.cinlude? value
  end

  def creator e
    s = el(:select)
    s.options = range
    s.to_s
  end
end


class DateRangeThing < Thing
  attribute :from, :to

  def initialize
    super()
    @range = DateRangeWidget.new(:name => (form_id :content))
  end

  def recieve e
    @range.recieve e.params
    @from = @range.from
    @to = @range.to
  end  

  def creator e
    @range.to_s
  end

  def from
    @range.from
  end

  def from= from
    @range.from = from
  end

  def to
    @range.to
  end

  def to= to
    @range.to = to
  end
end

class DateRangeWidget < Widget
  def initialize options
    super
    self << "od "
    self << @from = InputDate.new(:name => options[:name]+'_from')
    self << " do "
    self << @to = InputDate.new(:name => options[:name]+'_to')
  end

  def from
    @from.date
  end

  def to
    @to.date
  end

  def from= from
    @from.date = from
  end

  def to= to
    @to.date = to
  end
end